# -*- coding:utf-8 -*-
"""
@Author : 审心
@Time : 2023/3/22 14:23
机器人系统相关接口
"""
import json
import queue
import common.glv as glv
from autoTask.core.TaskThread import TaskThread
from autoTask.core.TaskThreadV2 import TaskThreadV2, start_task_thread_lock
from common.logger.log import log_, memory_handler
from .core.apiManage import apiMap
from flask import Blueprint, g as flask_glv
from .pojo.res import ok, err
import threading
from autoTask.operaitonAid.taobao.task_run_module.task_run import operaiton_add_title_and_add_keywords, \
    operaiton_add_title, \
    ztc_add_keywords, get_screen_shot, store_info_task, delay_exit_app
from common.utils.end_thread import async_raise

robot_api = Blueprint('robot', __name__)
thread_id = None
# 记录线程ID

if '确认服务器连接' in apiMap:
    @robot_api.route(apiMap["确认服务器连接"]['uri'], methods=['POST'])
    def confirm_conn():
        """
            确认服务器连接
        """
        return ok()

if "获取任务" in apiMap:
    @robot_api.route(apiMap["获取任务"]['uri'], methods=['POST'])
    def pull_task():
        global thread_id
        log_.info(f"获取到任务, 参数 : {flask_glv.params} ")
        # 获取解析当前模板
        v = flask_glv.params["template"]
        # 获取当前任务发起人id
        admin_id = flask_glv.params["adminId"]
        # 获取锁，确保只有一个线程可以进入下面的代码块
        try:
            with start_task_thread_lock:
                if glv.get_item("task_thread"):
                    return err("当前设备已有启动任务线程")
                log_.info(f"当前任务发起人编号 : {admin_id}")
                glv.set_item("admin_id", admin_id)
                task_snapshot = json.loads(v["taskConfigSnapshot"])
                # 启动任务线程
                task_thread = TaskThread(task_snapshot)
                glv.set_item("task_thread", task_thread)
                task_thread.start()
                thread_id = task_thread.ident
        except:
            glv.set_item("task_thread",None)
        return ok()

if "接收任务" in apiMap:
    @robot_api.route(apiMap["接收任务"]['uri'], methods=['POST'])
    def accept_task():
        try:
            global thread_id
            req_param = flask_glv.params
            # 获取锁，确保只有一个线程可以进入下面的代码块
            with start_task_thread_lock:
                if glv.get_item("task_thread"):
                    return err("当前设备已有启动任务线程")

                task_thread = TaskThreadV2(req_param)
                glv.set_item("task_thread", task_thread)
                task_thread.start()
                thread_id = task_thread.ident
        except:
            glv.set_item("task_thread", None)
        return ok()

if "添加标题与关键词" in apiMap:
    @robot_api.route(apiMap["添加标题与关键词"]['uri'], methods=['POST'])
    def operaiton_add_title_keywords():
        global thread_id
        log_.info(f"获取到任务, 参数 : {flask_glv.params} ")
        title_keywords_thread = threading.Thread(target=operaiton_add_title_and_add_keywords, args=[flask_glv.params])
        log_.info("执行开始")
        title_keywords_thread.start()
        log_.info("执行完毕")
        thread_id = title_keywords_thread.ident
        return ok()

if "获取截图" in apiMap:
    @robot_api.route(apiMap["获取截图"]['uri'], methods=['POST'])
    def get_screenshot() -> str:
        """
        获取任务截图
        :return:task_shot 任务截图base64
        """
        log_.info("获取到任务: 获取截图 ")
        result_queue = queue.Queue()
        screenshot_thread = threading.Thread(target=get_screen_shot, args=[result_queue])
        log_.info("执行开始")
        screenshot_thread.start()
        log_.info("截图完毕")
        task_shot = result_queue.get()
        return ok(data=task_shot)
if "获取日志" in apiMap:
    @robot_api.route(apiMap["获取日志"]['uri'], methods=['POST'])
    def get_log():
        """
        获取日志
        :return: 日志
        """
        log_.info("获取到任务: 获取日志 ")
        log_content = memory_handler.get_log_content()
        log_.info("获取日志完毕")
        return ok(data=log_content)

if "修改商品标题" in apiMap:
    @robot_api.route(apiMap["修改商品标题"]['uri'], methods=['POST'])
    def reset_title():
        global thread_id
        log_.info(f"获取到任务, 参数 : {flask_glv.params} ")
        my_thread = threading.Thread(target=operaiton_add_title, args=[flask_glv.params])
        log_.info("执行开始")
        my_thread.start()
        log_.info("执行完毕")
        thread_id = my_thread.ident
        return ok()

if "直通车加推广词" in apiMap:
    @robot_api.route(apiMap["直通车加推广词"]['uri'], methods=['POST'])
    def throughtrain_add_keywords():
        """
        直通车加关键词
        :return:
        """
        global thread_id
        log_.info(f"获取到任务, 参数 : {flask_glv.params}")
        my_thread = threading.Thread(target=ztc_add_keywords, args=[flask_glv.params])
        log_.info("执行开始")
        my_thread.start()
        log_.info("执行完毕")
        thread_id = my_thread.ident
        return ok()

if "结束任务" in apiMap:
    @robot_api.route(apiMap["结束任务"]['uri'], methods=['POST'])
    def stop_task():
        """
        结束任务
        :return:
        """
        global thread_id
        if thread_id is not None:
            async_raise(thread_id, SystemExit)
            thread_id = None
            # 成功结束线程后 将记录线程ID的参数置空
            log_.info("任务结束成功")
            return ok(data="任务结束成功")
        else:
            return ok(data="当前没有正在执行的任务")

if "获取店铺信息" in apiMap:
    @robot_api.route(apiMap["获取店铺信息"]['uri'], methods=['POST'])
    def get_shop_info():
        """
        获取店铺信息
        :return:
        """
        global thread_id
        log_.info(f"获取到任务:获取店铺信息, 参数 : {flask_glv.params} ")
        my_thread = threading.Thread(target=store_info_task, args=[flask_glv.params])
        log_.info("执行开始")
        my_thread.start()
        log_.info("执行完毕")
        thread_id = my_thread.ident
        return ok()

if "退出应用" in apiMap:
    @robot_api.route(apiMap["退出应用"]['uri'], methods=['POST'])
    def exit_app():
        """
        退出应用
        :return:
        """
        global thread_id
        threading.Thread(target=delay_exit_app, args=(3, thread_id)).start()
        # func = request.environ.get('shutdown')
        # if func is None:
        #     raise RuntimeError('退出失败')
        # func()

        log_.info("成功退出")
        return ok(data="成功退出")
